package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.common.utils.*;
import com.example.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    private static String VERIFICATION_CODE_PREFIX="VerificationCode";
    private static Long VERIFICATION_CODE_TIMEOUT=60L;
    private static String VERIFICATION_CODE_TEMPLATE_CODE="SMS_154950909";

    @Autowired
    private SMSUtil smsUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void sendVerificationCode(String phoneNumber) {
        //1.校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //2.生成验证码，调用MyCapture
        String code= MyCaptureUtil.getCapture(4);

        //3.发送验证码
        Map<String,String> map=new HashMap<>();
        map.put("code","code");
        if (StringUtils.hasText(code)){
            smsUtil.sendMessage(VERIFICATION_CODE_TEMPLATE_CODE,phoneNumber, JacksonUtil.writeValueAsString(map));
        }
        //4.缓存验证码
        redisUtil.set(VERIFICATION_CODE_PREFIX+phoneNumber,code,VERIFICATION_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        //1.校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX+phoneNumber);
    }
}
